package com.health.mapp.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.health.db.model.RegisterOrder;
import com.health.db.model.RegisterOrderExample;
import com.health.db.model.UserCardList;
import com.health.db.model.UserCardListExt;
import com.health.db.model.UserLIST;
import com.health.db.service.order.IRegisterOrderService;
import com.health.db.service.sm.IRongService;
import com.health.db.service.sm.ISMSSendService;
import com.health.db.service.user.IUserCardListService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.Header;
import com.health.mapp.bean.PayControllerSelfReq;
import com.health.mapp.bean.PayControllerSelfResp;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;

/**
 *  系统内预计开通多种支付方式
 *  此类支撑通过本系统内账户支付，包括用户钱包支付和用户服务卡支付
 *  钱包要充值，需要充值流程支撑
 *  用户服务卡要进行激活，需要卡激活流程支撑
 *  除此两种外,支撑第三方支付:微信和支付宝支付
 *  此类具体实现功能：付费，将等待支付订单修改为等待就诊状态
 *  钱包支付后，用户钱包内相应减少钱，减少的钱只存储于订单中，医生钱包内不会增加钱，订单完成后医生钱包内增加订单金额。订单平账
 *  用户服务卡支付后，用户服务卡内减少相应钱，减少的钱只存储于订单中，医生钱包内不会增加钱，订单完成后医生钱包内增加订单金额。订单平账
 *  用户发起第三方支付后，用户现金进入担保账户，用户微信或支付宝账户内金额减少。订单存储订单金额，医生钱包内不会增加钱，当订单完成后医生钱包内增加订单金额。订单平账
 *  医生发起提现后，系统从担保账户将钱转到医生银行账户、微信或是支付宝账户。全流程平账
 * @author HiRoad
 * 
 * @pramati
 * 	private Long  orderId; //订单号
 *  private int type;//0:钱包支付,1:服务卡支付
 *  钱包支付：
 *  
 *  卡支付：
 *  
 *
 */
public class PayControllerSelfImpl implements ActionInterface {
	
	//service import
	private IRegisterOrderService registerOrderService  ;
	private IUserLISTService userLISTService;
	private IUserCardListService userCardListService;
	private IRongService rongService;
	private ISMSSendService sMSSendService;
	
	@Override
	public Response execute(Header header, Object reqBean) throws Exception {
		
		PayControllerSelfReq req = (PayControllerSelfReq) reqBean; 
		PayControllerSelfResp _resp = new PayControllerSelfResp();
		Long orderId = req.getOrderId();
		//支付方式
		int type = req.getType();
		Long userId = req.getUserId();
		
		
		if (orderId==0 ) {
			_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ORDERID);
			_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ORDERID_NOTE);
			return _resp;
		}
		else if(userId.intValue()==0) {
			_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_USERID);
			_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_USERID_NOTE);
			return _resp;
		}
		 
		else
		{
			
			//获取当前要支付的订单
			RegisterOrder  currRegisterOrder =registerOrderService.selectSimpleSingleByOrderId(orderId);
			
			currRegisterOrder.setRegisterid(orderId);
			
			/*//判断订单状态 订单不存在或者是免费订单，或是订单状态不是等待支付
			if (currRegisterOrder==null||currRegisterOrder.getOrderfeetypeid()==Constant.CONSTANTS_ORDER_FREE_ID_0
					||!(currRegisterOrder.getRunstatusid()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_1)) {
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3001);
				_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3001_NOTE);
				return _resp;
			}*/
			if (currRegisterOrder==null) {
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3001);
				_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3001_NOTE);
				return _resp;
			}else if (currRegisterOrder.getOrderfeetypeid().intValue()==Constant.CONSTANTS_ORDER_FREE_ID_0.intValue()) {
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3001);
				_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3022_NOTE);
				return _resp;
			}
			if (!(currRegisterOrder.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_1.intValue())) {
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3001);
				_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3023_NOTE);
				return _resp;
			}else
			{
				if (type ==0) {
					
					int flag= -1;
					
					//查询到用户可用的卡列表，并返回离失效时间最近的一张卡
					UserCardListExt queryUserCardListExt =new UserCardListExt();
					queryUserCardListExt.setOwnerid(userId);
					
					//此处条件 只是为了去标记leftTime不为空 
					//取值的时候只会取判断leftTime>0
					queryUserCardListExt.setLefttime02(currRegisterOrder.getRegisterTotal());
					List<UserCardList> list =userCardListService.selectUserCardLists(queryUserCardListExt);
					
					if(null==list||list.size()==0 )
					{
						flag = -2;
						//flag= walletPayment(currRegisterOrder );
					}else{
						flag= walletPayment(currRegisterOrder ,list);
					}
					
					//总额度不足，提示使用其他支付方式。
					if (flag==Constant.CARD_PAYMENT_NOT_ENOUGH) {
						_resp.setErrorCode(ResultCode.OPERATION_WALLET_PAYMENT_NOT_ENOUGH_ERROR);
						_resp.setErrorMsg(ResultCode.OPERATION_WALLET_PAYMENT_NOT_ENOUGH_ERROR_NOTE);
						return _resp;
					}
				}
				else if (type==1) 
				{
					//服务卡支付
					 
					//查询到用户可用的卡列表，并返回离失效时间最近的一张卡
					UserCardListExt queryUserCardListExt =new UserCardListExt();
					queryUserCardListExt.setOwnerid(userId);
					
					int registerType= currRegisterOrder.getRegistertypeid();
					
					//增加剩余时间（次数，余额）校验，如果余额已为0 ，或是余额不够此次消费，则不返回
					if (registerType==Constant.CONSTANTS_ORDER_TYPE_ID_1.intValue()) 
					{
						queryUserCardListExt.setLefttime01(new BigDecimal(1));
					}
					else
					{
						// OrderBillTime未写入registe_order表
						queryUserCardListExt.setLefttime03(currRegisterOrder.getOrderBillTime());
					}
					
					List<UserCardList> list =userCardListService.selectUserCardLists(queryUserCardListExt);
					
					if(null==list||list.size()==0 )
					{
						_resp.setErrorCode(ResultCode.OPERATION_CARD_PAYMENT_NOT_ENOUGH_ERROR);
						_resp.setErrorMsg(ResultCode.OPERATION_CARD_PAYMENT_NOT_ENOUGH_ERROR_NOTE);
						return _resp;
					}
					
					
					//服务卡支付（或者叫什么其他的卡） -2 额度不足
					int flag= -1;
					flag= serviceCardPayment( userId, currRegisterOrder   ,list);
					
					//总额度不足，提示使用其他支付方式。
					if (flag==Constant.CARD_PAYMENT_NOT_ENOUGH) {
						_resp.setErrorCode(ResultCode.OPERATION_CARD_PAYMENT_NOT_ENOUGH_ERROR);
						_resp.setErrorMsg(ResultCode.OPERATION_CARD_PAYMENT_NOT_ENOUGH_ERROR_NOTE);
						return _resp;
					}
				}
				else{
					_resp.setErrorCode(ResultCode.OPERATION_UN_SUPPORT_PAYMENT_ERROR);
					_resp.setErrorMsg(ResultCode.OPERATION_UN_SUPPORT_PAYMENT_ERROR_NOTE);
					return _resp;
				}
				
				//融云推送
				String groupId = String.valueOf(currRegisterOrder.getRegisterid() );
				String[] userIds = {String.valueOf(userId)};
				rongService.createGroup(userIds, groupId, groupId);
				rongService.PublishSystemOrderToDocMsg(currRegisterOrder);
				
				//判断是否有客服
				if (StringUtils.isNotEmpty(currRegisterOrder.getSsMeasure())) {
					String[] assisIds = {currRegisterOrder.getSsMeasure()};
					rongService.joinGroup(assisIds, groupId, groupId);
					rongService.PublishSystemOrderToAssisMsg(String.valueOf(userId),currRegisterOrder.getSsMeasure(), groupId);
					
				}
				//视屏咨询
				if (currRegisterOrder.getRegistertypeid().intValue()!=Constant.CONSTANTS_ORDER_TYPE_ID_1.intValue()) {
					//SendSMS(currRegisterOrder);
					UserLIST docUser = userLISTService.selectByUserId(currRegisterOrder.getAccepterid());
					sMSSendService.regsiterOrder(docUser, currRegisterOrder);
				}
			}
		}
		
		_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
		_resp.setErrorMsg(ResultCode.OPERATION_SUCCESS_NOTE);
 
		return _resp;
	}

	
	
	public int serviceCardPayment(long userId,RegisterOrder  currRegisterOrder, List<UserCardList>  userCardList )
	{
		
		 
		    int registerType= currRegisterOrder.getRegistertypeid();
		    long  orderId=currRegisterOrder.getRegisterid();
		    
		    //准备入库的数据对象
		    RegisterOrder orderInfo = new RegisterOrder();
		    //返回对象
		    RegisterOrderExample registerOrderExample = new RegisterOrderExample();
			orderInfo.setRegisterid(orderId);
			orderInfo.setUserid(userId);
			orderInfo.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_2);
			orderInfo.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_2);
			//是否支付
			orderInfo.setRegisterPayFlag(Constant.CONSTANTS_IS_PAYMENT_TRUE);
			//支付方式
			orderInfo.setPayTypeId(Constant.CONSTANTS_PAYMENT_SERVICE_CARD);
			orderInfo.setRegistertypeid(currRegisterOrder.getRegistertypeid());
			
			//多卡支付的时候 只记录第一张卡信息
			
			//卡类型
			
			orderInfo.setOrderTypeDesc(currRegisterOrder.getOrderTypeDesc());
			orderInfo.setGoodsid(currRegisterOrder.getGoodsid());
			
            Date currDateTime=DateUtils.getDatetime();
			orderInfo.setUpdateDate(currDateTime);
			
			//String 初始化
			orderInfo.setCardJournalAmount("");
			orderInfo.setCardID("");
			orderInfo.setCardItemID("");
			//图文咨询
			if (registerType==Constant.CONSTANTS_ORDER_TYPE_ID_1.intValue()) {
				orderInfo.setCardJournalAmount("1");
				orderInfo.setCardID(String.valueOf(userCardList.get(0).getCardid()));
				orderInfo.setCardItemID("T"+Constant.PAYMENT_SERVICE_CARD_1);
				UserCardList userCard =userCardList.get(0);
				BigDecimal leftTime= userCard.getLefttime01();
				//更新 金额 和日期 ,卡号为条件
				userCard.setLefttime01(leftTime.subtract(new BigDecimal(1)));
				userCard.setUpdateDate(DateUtils.now());
				userCard.setCardid(userCard.getCardid());
				registerOrderExample = registerOrderService.updateOrder4CardPayment(orderInfo, userCard,Constant.PAYMENT_SERVICE_CARD_1);
			}else{
				//现在只是支付，所以订单剩余时间也是订单的总时间
				orderInfo.setOrderLeftTime(currRegisterOrder.getOrderBillTime());
				List<UserCardList>  userCardListForUpdate = new ArrayList<UserCardList>();
				
				int leftTime03=0;
				int consTime=currRegisterOrder.getOrderBillTime().intValue();
				
				int total=0;
				for (int i = 0; i < userCardList.size(); i++) {
					UserCardList userCard =userCardList.get(i);
					int cardLeftTime = userCard.getLefttime03().intValue();
					total= total+cardLeftTime;
					if (cardLeftTime<=0) {
						continue;
					}
					leftTime03 =cardLeftTime-consTime;
					
					if (leftTime03>=0) {
						//更新 金额 和日期 ,卡号为条件
						userCard.setLefttime03(new BigDecimal(leftTime03));
						userCard.setUpdateDate(DateUtils.now());
						userCard.setCardid(userCard.getCardid());
						userCardListForUpdate.add(userCard);
						orderInfo.setCardJournalAmount(orderInfo.getCardJournalAmount()+consTime);
						orderInfo.setCardID(orderInfo.getCardID()+userCard.getCardid());
						orderInfo.setCardItemID(orderInfo.getCardItemID()+"T"+Constant.PAYMENT_SERVICE_CARD_3);
						
						break;
					}else{
						
						//更新 金额 和日期 ,卡号为条件
						userCard.setLefttime03(new BigDecimal(0));
						userCard.setUpdateDate(DateUtils.now());
						userCard.setCardid(userCard.getCardid());
						userCardListForUpdate.add(userCard);
						orderInfo.setCardJournalAmount(orderInfo.getCardJournalAmount()+cardLeftTime+",");
						orderInfo.setCardID(orderInfo.getCardID()+userCard.getCardid()+",");
						orderInfo.setCardItemID(orderInfo.getCardItemID()+"T"+Constant.PAYMENT_SERVICE_CARD_3+",");
						
						consTime = Math.abs(leftTime03);
					}
					
				}
				
				if (total<currRegisterOrder.getOrderBillTime().intValue()) {
					return  Constant.CARD_PAYMENT_NOT_ENOUGH;
				}
			
				
				//多条选择批处理
				if (userCardListForUpdate.size()==1) {
					registerOrderExample = registerOrderService.updateOrder4CardPayment(orderInfo, userCardListForUpdate.get(0),Constant.PAYMENT_SERVICE_CARD_3);
				}else{
					registerOrderExample = registerOrderService.updateOrder4CardPayment(orderInfo, userCardListForUpdate,Constant.PAYMENT_SERVICE_CARD_3);
				}
			}
		 
			
			return  registerOrderExample.getUpdateNum();
	
	}
	
	
	/**
	 * 用户有激活卡，激活卡有实效
	 * @param currRegisterOrder
	 * @param userCardList
	 * @return
	 */
	public int walletPayment(RegisterOrder  currRegisterOrder, List<UserCardList>  userCardList )
	{

	    long  orderId=currRegisterOrder.getRegisterid();
	    
	    //准备入库的数据对象
	    RegisterOrder orderInfo = new RegisterOrder();
	    //返回对象
	    RegisterOrderExample registerOrderExample = new RegisterOrderExample();
		orderInfo.setRegisterid(orderId);
		orderInfo.setUserid(currRegisterOrder.getUserid());
		orderInfo.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_2);
		orderInfo.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_2);
		//是否支付
		orderInfo.setRegisterPayFlag(Constant.CONSTANTS_IS_PAYMENT_TRUE);
		//支付方式
		orderInfo.setPayTypeId(Constant.CONSTANTS_PAYMENT_WALLET);
		
		orderInfo.setOrderTypeDesc(currRegisterOrder.getOrderTypeDesc());
		orderInfo.setGoodsid(currRegisterOrder.getGoodsid());
		
		orderInfo.setUpdateDate(new Date());
		
		orderInfo.setRegisterTotal(currRegisterOrder.getRegisterTotal());
		orderInfo.setRegistertypeid(currRegisterOrder.getRegistertypeid());
		orderInfo.setRegisterNo(currRegisterOrder.getRegisterNo());
		orderInfo.setRegisterDate(currRegisterOrder.getRegisterDate());	
		
		//String 初始化
		orderInfo.setCardJournalAmount("");
		orderInfo.setCardID("");
		orderInfo.setCardItemID("");
		
		
		//现在只是支付，所以订单剩余时间也是订单的总时间
		orderInfo.setOrderLeftTime(currRegisterOrder.getOrderBillTime());
		List<UserCardList>  userCardListForUpdate = new ArrayList<UserCardList>();
		
		BigDecimal leftTime02=new BigDecimal(0);
		BigDecimal consTime=currRegisterOrder.getRegisterTotal();
		
		BigDecimal total=new BigDecimal(0);
		for (int i = 0; i < userCardList.size(); i++) {
			UserCardList userCard =userCardList.get(i);
			BigDecimal cardLeftTime = userCard.getLefttime02();
			
			if (null==cardLeftTime||  cardLeftTime.compareTo(new BigDecimal(0))<=0) {
				continue;
			}
			total= total.add(cardLeftTime);
			leftTime02 =cardLeftTime.subtract(consTime);
			
			if (leftTime02.compareTo(new BigDecimal(0))>=0) {
				//更新 金额 和日期 ,卡号为条件
				userCard.setLefttime02(leftTime02);
				userCard.setUpdateDate(DateUtils.now());
				userCard.setCardid(userCard.getCardid());
				userCardListForUpdate.add(userCard);
				orderInfo.setCardJournalAmount(orderInfo.getCardJournalAmount()+  String.valueOf(consTime.setScale(2,  BigDecimal.ROUND_HALF_UP)));
				orderInfo.setCardID(orderInfo.getCardID()+userCard.getCardid());
				orderInfo.setCardItemID(orderInfo.getCardItemID()+"T"+Constant.PAYMENT_SERVICE_CARD_2);
				
				break;
			}else{
				
				//更新 金额 和日期 ,卡号为条件
				userCard.setLefttime02(new BigDecimal(0));
				userCard.setUpdateDate(DateUtils.now());
				userCard.setCardid(userCard.getCardid());
				userCardListForUpdate.add(userCard);
				orderInfo.setCardJournalAmount(orderInfo.getCardJournalAmount()+ String.valueOf(cardLeftTime.setScale(2,  BigDecimal.ROUND_HALF_UP)) +",");
				orderInfo.setCardID(orderInfo.getCardID()+userCard.getCardid()+",");
				orderInfo.setCardItemID(orderInfo.getCardItemID()+"T"+Constant.PAYMENT_SERVICE_CARD_2+",");
				
				consTime = new BigDecimal( Math.abs(leftTime02.doubleValue()));
			}
				
		}
		
		//多条数据卡支付不足的时候会已","结尾 删除","
		if (orderInfo.getCardJournalAmount().endsWith(",")) {
			orderInfo.setCardJournalAmount(orderInfo.getCardJournalAmount().substring(0, orderInfo.getCardJournalAmount().length()-1));
			orderInfo.setCardID(orderInfo.getCardID().substring(0,orderInfo.getCardID().length()-1));
			orderInfo.setCardItemID(orderInfo.getCardItemID().substring(0,orderInfo.getCardItemID().length()-1));
		}
		if (total.compareTo(currRegisterOrder.getRegisterTotal()) < 0) {

			return -2;
			
			//卡额度不够需要用余额来补充
			/*orderInfo.setCardJournalAmount(orderInfo.getCardJournalAmount() +","+String.valueOf(currRegisterOrder.getRegisterTotal().subtract(total).setScale(2,  BigDecimal.ROUND_HALF_UP)) );
			orderInfo.setCardID(orderInfo.getCardID()+",0");
			orderInfo.setCardItemID(orderInfo.getCardItemID()+",P");
			// 多条选择批处理
			if (userCardListForUpdate.size() == 1) {
				//多条数据卡支付不足的时候会已","结尾 删除","
				registerOrderExample = registerOrderService.updateOrder4WalletAndCardPayment(orderInfo,
								userCardListForUpdate.get(0),Constant.PAYMENT_SERVICE_CARD_2,
								currRegisterOrder.getRegisterTotal().subtract(total));
			} else {
				registerOrderExample = registerOrderService.updateOrder4WalletAndCardPayment(orderInfo,
								userCardListForUpdate,Constant.PAYMENT_SERVICE_CARD_2,
								currRegisterOrder.getRegisterTotal().subtract(total));
			}*/

		} else {
			// 多条选择批处理
			if (userCardListForUpdate.size() == 1) {
				registerOrderExample = registerOrderService.updateOrder4CardPayment(orderInfo,
								userCardListForUpdate.get(0),Constant.PAYMENT_SERVICE_CARD_2);
			} else {
				registerOrderExample = registerOrderService.updateOrder4CardPayment(orderInfo,
								userCardListForUpdate,Constant.PAYMENT_SERVICE_CARD_2);
			}
		}
		
		
		return  registerOrderExample.getUpdateNum();
	}
	
	
	/**
	 * 纯余额支付
	 * @param currRegisterOrder
	 * @return
	 */
	public int walletPayment(RegisterOrder  currRegisterOrder)
	{

	    long  orderId=currRegisterOrder.getRegisterid();
	    
	    //准备入库的数据对象
	    RegisterOrder orderInfo = new RegisterOrder();
	    //返回对象
	    RegisterOrderExample registerOrderExample = new RegisterOrderExample();
		orderInfo.setRegisterid(orderId);
		orderInfo.setUserid(currRegisterOrder.getUserid());
		orderInfo.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_2);
		orderInfo.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_2);
		//是否支付
		orderInfo.setRegisterPayFlag(Constant.CONSTANTS_IS_PAYMENT_TRUE);
		//支付方式
		orderInfo.setPayTypeId(Constant.CONSTANTS_PAYMENT_WALLET);
		
		orderInfo.setOrderTypeDesc(currRegisterOrder.getOrderTypeDesc());
		orderInfo.setGoodsid(currRegisterOrder.getGoodsid());
		
		orderInfo.setUpdateDate(new Date());
		
		orderInfo.setRegisterTotal(currRegisterOrder.getRegisterTotal());
		orderInfo.setRegistertypeid(currRegisterOrder.getRegistertypeid());
		orderInfo.setRegisterNo(currRegisterOrder.getRegisterNo());
		orderInfo.setRegisterDate(currRegisterOrder.getRegisterDate());	
		
		registerOrderExample=registerOrderService.updateOrder4WalletPayment(orderInfo);
		
		return  registerOrderExample.getUpdateNum();
	}
	
	
	public IRegisterOrderService getRegisterOrderService() {
		return registerOrderService;
	}

	public void setRegisterOrderService(IRegisterOrderService registerOrderService) {
		this.registerOrderService = registerOrderService;
	}

	/**
	 * @return the userLISTService
	 */
	public IUserLISTService getUserLISTService() {
		return userLISTService;
	}

	/**
	 * @param userLISTService the userLISTService to set
	 */
	public void setUserLISTService(IUserLISTService userLISTService) {
		this.userLISTService = userLISTService;
	}

	/**
	 * @return the userCardListService
	 */
	public IUserCardListService getUserCardListService() {
		return userCardListService;
	}

	/**
	 * @param userCardListService the userCardListService to set
	 */
	public void setUserCardListService(IUserCardListService userCardListService) {
		this.userCardListService = userCardListService;
	}




	/**
	 * @return the rongService
	 */
	public IRongService getRongService() {
		return rongService;
	}




	/**
	 * @param rongService the rongService to set
	 */
	public void setRongService(IRongService rongService) {
		this.rongService = rongService;
	}


	public ISMSSendService getsMSSendService() {
		return sMSSendService;
	}


	public void setsMSSendService(ISMSSendService sMSSendService) {
		this.sMSSendService = sMSSendService;
	}

}
